<template>
	<view class="user-management">
		<!-- 筛选栏 -->
		<view class="filter-bar">
			<picker 
				:range="roleOptions" 
				range-key="name"
				:value="roleIndex"
				@change="onRoleChange"
			>
				<view class="filter-item">
					<text>{{ roleOptions[roleIndex].name }}</text>
					<text class="arrow">▼</text>
				</view>
			</picker>
			
			<picker 
				:range="statusOptions" 
				range-key="name"
				:value="statusIndex"
				@change="onStatusChange"
			>
				<view class="filter-item">
					<text>{{ statusOptions[statusIndex].name }}</text>
					<text class="arrow">▼</text>
				</view>
			</picker>
		</view>
		
		<!-- 用户列表 -->
		<scroll-view 
			class="user-scroll" 
			scroll-y 
			@scrolltolower="loadMore"
			refresher-enabled 
			:refresher-triggered="refreshing"
			@refresherrefresh="onRefresh"
		>
			<view class="user-item" v-for="user in userList" :key="user.id">
				<view class="user-info">
					<view class="avatar">
						<text class="avatar-text">{{ user.realName ? user.realName.charAt(0) : (user.username ? user.username.charAt(0) : 'U') }}</text>
					</view>
					<view class="info">
						<text class="name">{{ user.realName || user.username }}</text>
						<text class="username">@{{ user.username }}</text>
						<text class="role">{{ getRoleName(user.roleType) }}</text>
					</view>
				</view>
				
				<view class="user-details">
					<view class="detail-row" v-if="user.phone">
						<text class="label">手机：</text>
						<text class="value">{{ user.phone }}</text>
					</view>
					<view class="detail-row" v-if="user.email">
						<text class="label">邮箱：</text>
						<text class="value">{{ user.email }}</text>
					</view>
					<view class="detail-row">
						<text class="label">注册时间：</text>
						<text class="value">{{ formatTime(user.createTime) }}</text>
					</view>
				</view>
				
				<view class="user-actions">
					<text class="status" :class="getStatusClass(user.status)">
						{{ getStatusText(user.status) }}
					</text>
					
					<button 
						class="action-btn" 
						:class="user.status === 1 ? 'disable' : 'enable'"
						@click="toggleUserStatus(user)"
					>
						{{ user.status === 1 ? '禁用' : '启用' }}
					</button>
				</view>
			</view>
			
			<view class="load-more" v-if="hasMore">
				<text v-if="loading">加载中...</text>
				<text v-else>上拉加载更多</text>
			</view>
			
			<view class="no-more" v-if="!hasMore && userList.length > 0">
				<text>没有更多数据了</text>
			</view>
			
			<view class="empty" v-if="!loading && userList.length === 0">
				<text>暂无用户数据</text>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				userList: [],
				loading: false,
				refreshing: false,
				hasMore: true,
				pageNum: 1,
				pageSize: 10,
				roleIndex: 0,
				statusIndex: 0,
				roleOptions: [
					{ name: '全部角色', value: '' },
					{ name: '管理员', value: 1 },
					{ name: '派单员', value: 2 },
					{ name: '用户', value: 3 },
					{ name: '技术员', value: 4 }
				],
				statusOptions: [
					{ name: '全部状态', value: '' },
					{ name: '正常', value: 1 },
					{ name: '禁用', value: 0 }
				]
			}
		},
		onLoad() {
			if (this.checkPermission()) {
				this.loadUsers()
			}
		},
		methods: {
			checkPermission() {
				// 检查store是否存在
				if (!this.$store) {
					console.log('Store未初始化')
					uni.reLaunch({
						url: '/pages/login/login'
					})
					return false
				}
				
				// 检查是否已登录
				if (!this.$store.getters.isLogin) {
					console.log('用户未登录')
					uni.reLaunch({
						url: '/pages/login/login'
					})
					return false
				}
				
				// 检查是否是管理员
				if (!this.$store.getters.isAdmin) {
					uni.showToast({
						title: '权限不足，需要管理员权限',
						icon: 'none'
					})
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
					return false
				}
				
				return true
			},
			
			async loadUsers(refresh = false) {
				if (this.loading) return
				
				this.loading = true
				
				if (refresh) {
					this.pageNum = 1
					this.hasMore = true
				}
				
				try {
					const params = {
						pageNum: this.pageNum,
						pageSize: this.pageSize
					}
					
					if (this.roleOptions[this.roleIndex].value) {
						params.roleType = this.roleOptions[this.roleIndex].value
					}
					
					if (this.statusOptions[this.statusIndex].value !== '') {
						params.status = this.statusOptions[this.statusIndex].value
					}
					
					const res = await this.$api.getUserList(params)
					
					if (res.code === 200) {
						const newUsers = res.data || []
						
						if (refresh) {
							this.userList = newUsers
						} else {
							this.userList = [...this.userList, ...newUsers]
						}
						
						this.hasMore = newUsers.length === this.pageSize
						this.pageNum++
					}
				} catch (error) {
					uni.showToast({
						title: error.message || '加载失败',
						icon: 'none'
					})
				} finally {
					this.loading = false
					this.refreshing = false
				}
			},
			
			onRefresh() {
				this.refreshing = true
				this.loadUsers(true)
			},
			
			loadMore() {
				if (this.hasMore && !this.loading) {
					this.loadUsers()
				}
			},
			
			onRoleChange(e) {
				this.roleIndex = e.detail.value
				this.loadUsers(true)
			},
			
			onStatusChange(e) {
				this.statusIndex = e.detail.value
				this.loadUsers(true)
			},
			
			async toggleUserStatus(user) {
				const newStatus = user.status === 1 ? 0 : 1
				const action = newStatus === 1 ? '启用' : '禁用'
				
				uni.showModal({
					title: `确认${action}`,
					content: `确定要${action}用户"${user.realName || user.username}"吗？`,
					success: async (res) => {
						if (res.confirm) {
							try {
								await this.$api.updateUserStatus(user.id, newStatus)
								
								// 更新本地数据
								const index = this.userList.findIndex(item => item.id === user.id)
								if (index !== -1) {
									this.userList[index].status = newStatus
								}
								
								uni.showToast({
									title: `${action}成功`,
									icon: 'success'
								})
							} catch (error) {
								uni.showToast({
									title: error.message || `${action}失败`,
									icon: 'none'
								})
							}
						}
					}
				})
			},
			
			getRoleName(roleType) {
				const roleMap = {
					1: '管理员',
					2: '派单员',
					3: '用户',
					4: '技术员'
				}
				return roleMap[roleType] || '未知'
			},
			
			getStatusClass(status) {
				return status === 1 ? 'status-active' : 'status-disabled'
			},
			
			getStatusText(status) {
				return status === 1 ? '正常' : '禁用'
			},
			
			formatTime(time) {
				if (!time) return ''
				const date = new Date(time)
				return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
			}
		}
	}
</script>

<style lang="scss" scoped>
	.user-management {
		height: 100vh;
		display: flex;
		flex-direction: column;
		background: #f5f5f5;
	}
	
	.filter-bar {
		background: #fff;
		padding: 20rpx;
		display: flex;
		gap: 20rpx;
		border-bottom: 1rpx solid #eee;
		flex-wrap: wrap;
		
		.filter-item {
			flex: 1;
			min-width: 200rpx;
			max-width: calc(50% - 10rpx);
		}
		
		@media (max-width: 750rpx) {
			.filter-item {
				min-width: 100%;
				max-width: 100%;
			}
		}
		
		.filter-item {
			flex: 1;
			padding: 20rpx;
			background: #f8f8f8;
			border-radius: 10rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 28rpx;
			
			.arrow {
				color: #999;
				font-size: 20rpx;
			}
		}
	}
	
	.user-scroll {
		flex: 1;
		padding: 20rpx;
	}
	
	.user-item {
		background: #fff;
		border-radius: 15rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
		
		.user-info {
			display: flex;
			align-items: center;
			margin-bottom: 20rpx;
			
			.avatar {
				width: 80rpx;
				height: 80rpx;
				border-radius: 40rpx;
				background: linear-gradient(45deg, #667eea, #764ba2);
				display: flex;
				align-items: center;
				justify-content: center;
				margin-right: 30rpx;
				
				.avatar-text {
					font-size: 28rpx;
					font-weight: bold;
					color: #fff;
				}
			}
			
			.info {
				flex: 1;
				
				.name {
					display: block;
					font-size: 32rpx;
					font-weight: bold;
					color: #333;
					margin-bottom: 8rpx;
				}
				
				.username {
					display: block;
					font-size: 24rpx;
					color: #666;
					margin-bottom: 8rpx;
				}
				
				.role {
					font-size: 24rpx;
					color: #007AFF;
					background: rgba(0, 122, 255, 0.1);
					padding: 4rpx 12rpx;
					border-radius: 12rpx;
				}
			}
		}
		
		.user-details {
			margin-bottom: 20rpx;
			
			.detail-row {
				display: flex;
				margin-bottom: 10rpx;
				
				&:last-child {
					margin-bottom: 0;
				}
				
				.label {
					font-size: 24rpx;
					color: #666;
					width: 120rpx;
				}
				
				.value {
					flex: 1;
					font-size: 24rpx;
					color: #333;
				}
			}
		}
		
		.user-actions {
			display: flex;
			justify-content: space-between;
			align-items: center;
			
			.status {
				font-size: 24rpx;
				padding: 6rpx 16rpx;
				border-radius: 15rpx;
				
				&.status-active {
					color: #28a745;
					background: rgba(40, 167, 69, 0.1);
				}
				
				&.status-disabled {
					color: #dc3545;
					background: rgba(220, 53, 69, 0.1);
				}
			}
			
			.action-btn {
				width: 120rpx;
				height: 60rpx;
				border: none;
				border-radius: 30rpx;
				font-size: 24rpx;
				
				&.enable {
					background: #28a745;
					color: #fff;
				}
				
				&.disable {
					background: #dc3545;
					color: #fff;
				}
			}
		}
	}
	
	.load-more, .no-more {
		text-align: center;
		padding: 40rpx 0;
		color: #999;
		font-size: 28rpx;
	}
	
	.empty {
		text-align: center;
		padding: 200rpx 0;
		color: #999;
		font-size: 28rpx;
	}
</style>